package com.tzinfo.tztbase;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.JudgeStatusResult;
import com.tzinfo.data.TztData;
import com.tzinfo.data.UserInfo;
import com.tzinfo.tzb.ManagementActivity;
import com.tzinfo.tzb.TzbBangForumpostListActivity;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.HouseNewsDetailActivity;
import com.tzinfo.tzt.util.HttpUtils;
import com.tzinfo.tztbase.index.TztBaseIndex;
import com.tzinfo.tztbase.util.DataSaveTools;
import com.tzinfo.tztbase.util.DefaultResult;
import com.tzinfo.tztbase.util.GPSThread;
import com.yxw.util.OutLog;
import com.yxw.view.util.ResFinder;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class TztBaseMainActivity extends Activity {

    // UI组件
    private Button bt_login;
    private Button bt_manager;
    public final static String Subject_PUSH = "subject";
    public final static String House_PUSH = "house";
    private Intent intentFromServerPush = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tztbase_ac_main);
        intentFromServerPush = getIntent();
        // 获取GPS
        if (TztData.location == null) {
            // MyApplication.location = new GPSTools(this).getLocation();
            GPSThread.getInstance(this).requestLocation();
        }
        // 获取手机的分辨率
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        TztData.widthPixels = dm.widthPixels;
        TztData.heightPixels = dm.heightPixels;
        init();
        if (TztData.userInfo == null){
            autoLogin();
        }else {
            checkLoginUI();
        }

        if (TztData.userInfo != null)
            new JudgeStatus().execute();
        if (Subject_PUSH.equals(intentFromServerPush.getSerializableExtra("open_flag"))) {
            goSubject();
        }
        if (House_PUSH.equals(intentFromServerPush.getSerializableExtra("open_flag"))) {
            goHouse();
        }
    }

    public void goSubject() {
        Intent i = new Intent();
        i.putExtra("FID", intentFromServerPush.getStringExtra("fid"));
        i.putExtra("TID", intentFromServerPush.getStringExtra("tid"));
        i.putExtra("isNotification", true);
        i.putExtra("Subject", intentFromServerPush.getStringExtra("Subject"));
        i.setClass(this, TzbBangForumpostListActivity.class);
        startActivity(i);
        finish();
    }

    public void goHouse() {
        Intent i = new Intent();
        i.putExtra("houseNewsId", intentFromServerPush.getStringExtra("houseNewsId"));
        i.setClass(this, HouseNewsDetailActivity.class);
        startActivity(i);
        finish();
    }

    public void init() {
        bt_login = (Button) findViewById(R.id.bt_login);
        bt_manager = (Button) findViewById(R.id.bt_manager);
        bt_manager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TztBaseMainActivity.this, ManagementActivity.class);
                startActivity(intent);

            }
        });
    }

    public void autoLogin() {

        Map<String, String> map = DataSaveTools
                .getLoginInfo(TztBaseMainActivity.this);
        if (map != null) {
            GalHttpRequest galHttpRequest = new GalHttpRequest(this);
            galHttpRequest.setCacheEnable(false);
            String url = "http://member.tzinfo.net/mob/api/Login.ashx"
                    + "?usertype=0&" + "username=" + map.get(TztData.USER_NAME)
                    + "&" + "password=" + map.get(TztData.USER_PASSWORD);
            galHttpRequest.setURL(url);
            OutLog.LogE("url", url);
            galHttpRequest
                    .startAsynRequestString(new GalHttpLoadTextCallBack() {

                        @Override
                        public void textLoaded(String arg0) {
                            OutLog.LogE("JsonString", arg0 + "");
                            Gson gson = new Gson();
                            java.lang.reflect.Type type = new TypeToken<UserInfo>() {
                            }.getType();
                            UserInfo userInfo = gson.fromJson(arg0, type);
                            OutLog.LogE("userInfo", userInfo.toString());
                            if (userInfo.getSuccess()) {
                                TztData.isUserLogin = true;
                                TztData.userInfo = userInfo;
                                Toast.makeText(getApplicationContext(),
                                        "已自动登录！", Toast.LENGTH_SHORT).show();
                                requestUserPosition(TztBaseMainActivity.this);
                                new JudgeStatus().execute();
                            } else {
                                // DataSaveTools.clearLoginInfo(TztBaseMainActivity.this);
                                Toast.makeText(getApplicationContext(),
                                        "自动登录失败！", Toast.LENGTH_SHORT).show();
                            }
                            checkLoginUI();
                        }
                    });
        }

    }

    public class JudgeStatus extends AsyncTask<String, Void, JudgeStatusResult> {


        @Override
        protected JudgeStatusResult doInBackground(String... params) {
            JudgeStatusResult result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("Sessionid", TztData.userInfo.getData().getSessionID()));

            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/Userstate_authority.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, JudgeStatusResult.class);

            return result;
        }

        @Override
        protected void onPostExecute(JudgeStatusResult result) {
            super.onPostExecute(result);
            if (result.getData().size() > 0)
                if (result.getData().get(0).getStatus() == 1) {
                    bt_manager.setVisibility(View.VISIBLE);
                }

        }
    }

    public static void requestUserPosition(Context context) {
        GalHttpRequest galHttpRequest = new GalHttpRequest(context);
        galHttpRequest.setCacheEnable(false);
        String url = ResFinder.getResString(context,
                "R.string.tzb_url_UserPositionAdd")
                + "?sessionid="
                + TztData.userInfo.getData().getSessionID()
                + "&mapx="
                + TztData.longitude + "&mapy=" + TztData.latitude;
        galHttpRequest.setURL(url);
        OutLog.LogE("yxw", url);
        galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                OutLog.LogE("yxw", "json:" + arg0);
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
                }.getType();
                DefaultResult temp = gson.fromJson(arg0, type);
                if (temp.isSuccess()) {// 坐标上传成功
                    // OutLog.LogE("yxw",
                    // "坐标x:"+TztData.longitude+"--"+"坐标x:"+TztData.longitude);
                }
            }
        });
    }

    // 修改登录注销按钮
    private void checkLoginUI() {
        if (TztData.isUserLogin) {
            if (TztData.userInfo != null)
            new JudgeStatus().execute();
            bt_login.setText("注销");
        } else {
            bt_login.setText("登录");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkLoginUI();
    }

    // 登录
    public void goLogin(View v) {
        if (!TztData.isUserLogin) {
            Intent intent = new Intent(this, TztBaseLoginActivity.class);
            startActivityForResult(intent, 1);
            logout();
        } else {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("确定注销登录吗？")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    TztData.userInfo = null;
                                    TzbCommonData.userInfoModel = null;
                                    TztData.isUserLogin = false;
                                    bt_manager.setVisibility(View.GONE);
                                    DataSaveTools
                                            .clearLoginInfo(TztBaseMainActivity.this);
                                    checkLoginUI();
                                }
                            })
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                }
                            }).show();
        }

    }

    public void logout() {
        TzbCommonData.POSITION = 0;
        TzbCommonData.faxianUserMap = null;
        TzbCommonData.notificationListMap = null;
        TzbCommonData.diaryList = null;
        TzbCommonData.diaryItem = 0;
        TzbCommonData.userInfoModel = null;
    }

    // 房产板块
    public void onIndexHouse(View v) {
        Intent intent = null;
        if (TztBaseIndex.activtyHouse != null) {
            intent = new Intent(this, TztBaseIndex.activtyHouse);
            startActivity(intent);
        } else {
            Toast.makeText(this, "您还没初始化目的Activity", Toast.LENGTH_SHORT).show();
        }
    }

    // 汽车板块
    public void onIndexCar(View v) {
        Intent intent = null;
        if (TztBaseIndex.activtyCar != null) {
            intent = new Intent(this, TztBaseIndex.activtyCar);
            startActivity(intent);
        } else {
            Toast.makeText(this, "您还没初始化目的Activity", Toast.LENGTH_SHORT).show();
        }
    }

    // 台州帮
    public void onIndexBang(View v) {
        Intent intent = null;
        if (TztBaseIndex.activtyBang != null) {
            intent = new Intent(this, TztBaseIndex.activtyBang);

            startActivity(intent);
        } else {
            intent = new Intent();
            intent.setClassName("com.tzinfo.tzb",
                    "com.tzinfo.tzb.TzbMainActivity");
            startActivity(intent);
        }
    }

    public void onIndexPeixun(View v) {
        Intent intent = null;
        if (TztBaseIndex.activtyPeixun != null) {
            intent = new Intent(this, TztBaseIndex.activtyPeixun);
            startActivity(intent);
        } else {
            Toast.makeText(this, "您还没初始化目的Activity", Toast.LENGTH_SHORT).show();
        }
    }

    public void onIndexSearch(View v) {
        Intent intent = null;
        if (TztBaseIndex.activtySearch != null) {
            intent = new Intent(this, TztBaseIndex.activtySearch);
            startActivity(intent);
        } else {
            Toast.makeText(this, "您还没初始化目的Activity", Toast.LENGTH_SHORT).show();
        }
    }

    // 退出提示框
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            new AlertDialog.Builder(TztBaseMainActivity.this)
                    .setTitle("提示")
                    .setMessage("确认退出？")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    TztData.isUserLogin = false;
                                    finish();
                                }
                            })
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                }
                            }).show();
            return false;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == 2) {
                new JudgeStatus().execute();
                checkLoginUI();
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}
